<?php
namespace app\common\util;

use Predis\Client;


/**
 * Class RedisBuilder
 * @package util
 * redis构造器
 */
class RedisClient
{

    /**
     * @var
     * 单例
     */
    private static $instance = null;

    /**
     * @var
     * 配置信息
     */
    private $_config;

    /**
     * RedisClient constructor.
     * 初始化
     */
    public function __construct()
    {
        $this->_config = [
            'host'       => '', // Redis服务器地址
            'port'       =>  6379,       // Redis端口
            'password'   =>  '',         // Redis密码，如无则留空
            'select'     =>  0,          // 使用哪一个数据库
            'timeout'    =>  0,          // 连接超时时间
            'expire'     =>  0,          // 缓存有效期(秒)
            'persistent' => false,       // 是否长连接
            'prefix' => 0,
        ];
    }

    /**
     * @return Client|null
     * 获取单例
     */
    public static function getInstance(): ?Client
    {
        if (is_null(self::$instance)) {
            $self = new self();
            return new Client([
                'scheme' => 'tcp',
                'host' => $self->_config['host'],
                'port' => $self->_config['port']
            ], [
                'prefix' => $self->_config['prefix'],
                'parameters' => [
                    'password' => $self->_config['password'],
                    'database' => $self->_config['select']
                ]
            ]);
        }
        return self::$instance;
    }
}